#include <iostream>
#include "log.hpp"
#include "InetAddr.hpp"
#include <string>
#include "Common.hpp"

using namespace LogModule;

int main(int argc, char *argv[])
{
    // 判断命令行参数是否符合要求
    if (argc != 3)
    {
        std::cout << "Client IP Port" << std::endl;
        exit(ExitCode::USAGE_ERR);
    }
    uint16_t port = std::stoi(argv[2]);
    std::string ip = argv[1];
    // 创建客户端套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    // 客户端无需进行显示的绑定
    InetAddr addr(ip, port);
    // 建立于服务器的连接
    int n = connect(sockfd, addr.GetAddr(), addr.SockLen());
    if (n < 0)
    {
        std::cout << "connect error" << std::endl;
        exit(ExitCode::CONNECT_ERR);
    }

    // 存储接收数据的缓冲区
    char buffer[4096];
    while (1)
    {
        std::cout << "please input:";
        std::string input;
        std::getline(std::cin, input);

        if (input == "QUIT")
        {
            break;
        }
        // 发送数据到服务器
        int n = write(sockfd, input.c_str(), input.size());
        if (n < 0)
        {
            std::cout << "write error" << std::endl;
        }
        // 从服务器当中得到数据
        n = read(sockfd, buffer, sizeof(buffer));
        if (n < 0)
        {
            std::cout << "read error" << std::endl;
            exit(ExitCode::READ_ERR);
        }
        else if (n > 0)
        {
            buffer[n] = 0;
            //std::cout << "Server say:" << buffer << std::endl;
            std::cout <<  buffer << std::endl;

        }
        else
        {
            std::cout << "Server quit" << std::endl;
            exit(ExitCode::READ_ERR);
        }
    }

    close(sockfd);

    return 0;
}